/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.event;

import com.inyourcode.core.util.StackTraceUtil;
import com.inyourcode.core.event.api.EventClazz;
import com.inyourcode.core.event.api.EventMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author JackLei
 */
public class EventSystem {
    private static final Logger LOGGER  = LoggerFactory.getLogger(EventSystem.class);
    private static final Map<String, List<EventProxy>> eventMap = new HashMap<>();

    public static void init(ApplicationContext applicationContext) {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(EventClazz.class);
        beansWithAnnotation.forEach((k,obj) ->{
            Method[] declaredMethods = obj.getClass().getDeclaredMethods();
            for (Method method : declaredMethods) {
                if (method.isAnnotationPresent(EventMethod.class)) {
                    EventMethod annotation = method.getAnnotation(EventMethod.class);
                    EventProxy eventProxy = new EventProxy(annotation.name(), method, obj, annotation.priority());
                    EventSystem.on(eventProxy);
                }
            }
        });

        eventMap.forEach((k,events) -> {
            Collections.sort(events);
        });
    }

    public static void on(EventProxy eventProxy) {
        String name = eventProxy.getName();
        List<EventProxy> eventProxies = eventMap.get(name);
        if (eventProxies == null) {
            eventProxies = new ArrayList<>();
            eventMap.put(name, eventProxies);
        }

        eventProxies.add(eventProxy);
    }

    public static void emit(String eventName, Object arg) {
        List<EventProxy> eventProxies = eventMap.get(eventName);
        if (eventProxies == null) {
            LOGGER.warn("Event emit waring.No monitoring for this event[{}]", eventName);
            return;
        }

        eventProxies.forEach(e->{
            try {
                e.invoke(arg);
            } catch (InvocationTargetException e1) {
                LOGGER.error("Event[{}] emit failed with exception,exception:{}", eventName, StackTraceUtil.stackTrace(e1));
            } catch (IllegalAccessException e2) {
                LOGGER.error("Event[{}] emit failed with exception,exception:{}", eventName, StackTraceUtil.stackTrace(e2));
            }
        });
    }


}
